/**
 * 将字节数格式化为可读字符串
 * @param bytes
 * @param digits 保留小数位数
 */
export function formatBytes(bytes: number, digits = 1): string {
  // 处理非数字输入
  if (typeof bytes !== "number" || isNaN(bytes)) {
    return `${(0).toFixed(digits)}B`;
  }

  const units = ["B", "KB", "MB", "GB"];
  let index = 0;
  let sign = bytes < 0 ? "-" : ""; // 保留负号
  bytes = Math.abs(bytes);

  // 逐级转换单位
  while (bytes >= 1024 && index < units.length - 1) {
    bytes /= 1024;
    index++;
  }

  // 返回格式化结果，保留两位小数
  return `${sign}${bytes.toFixed(digits)}${units[index]}`;
}

export function formatBytes1(bytes: number, decimals = 2) {
  if (bytes === 0) {
    return '0 Bytes';
  }

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${Number.parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`;
}
